package com.hzit.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.hzit.pojo.R;
import com.hzit.pojo.Student;
import com.hzit.service.StudentService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentService studentService;
	@Override
	public void init() throws ServletException {
		//1. 在servlet容器中取得spring容器
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		//2. 从spring容器中取得javaBean
		studentService = wac.getBean(StudentService.class);
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 处理post请求的中文乱码
		req.setCharacterEncoding("UTF-8");
		//2. 得到请求处理参数cmd(用于区分多个操作[添加 修改 删除 列表])
		String cmd = req.getParameter("cmd");
		//3. 判断是否有值(非空验证)
		if (StrUtil.isNotBlank(cmd)) {  // 相当于: cmd != null && !"".equals(cmd)
			if("list".equals(cmd)){
				list(req,resp);
			}

		}
	}
	//2. 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		//2.1 查询所有的学生列表
		List<Student> students = studentService.findAll();
		//2.2 将学生列表放到请求作用域中
		req.setAttribute("students",students);
		//2.3 进行页面的转发
		req.getRequestDispatcher("/index.jsp").forward(req,resp);
	}
}
